package com.py.credit.controller;

import java.io.BufferedOutputStream;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.py.credit.common.logs.ExceptionLogger;
import com.py.credit.common.rest.RestServiceResult;
import com.py.credit.entity.Column;
import com.py.credit.entity.DeclarationManagementForm;
import com.py.credit.entity.SysUser;
import com.py.credit.entity.Table;
import com.py.credit.entity.TableResult;
import com.py.credit.entity.enums.ModifyLogEnum;
import com.py.credit.service.BatchLogService;
import com.py.credit.service.ContentService;
import com.py.credit.service.DeclarationManagementFormService;
import com.py.credit.service.DissentAppealSeervice;
import com.py.credit.service.RemoteBaseService;
import com.py.credit.service.StepLogService;
import com.py.credit.service.TableService;
import com.py.credit.service.excel.read.service.ExcelReadService;
import com.py.credit.utils.DateUtils;
import com.py.credit.utils.FileUtil;
import com.py.credit.utils.FileUtils;
import com.py.credit.utils.MapCache;
import com.py.framework.core.annotation.IgnoreAuthority;
import com.py.framework.core.common.Page;
import com.py.framework.core.helper.HttpServletHelper;

import cn.hutool.core.codec.Base64;
import cn.hutool.core.util.CharsetUtil;

@RestController
@RequestMapping(value = "/DeclarationManagementForm")
public class DeclarationManagementFormController extends BaseController {

	@Autowired
	private DeclarationManagementFormService declarationManagementFormService;
	@Autowired
	private TableService tableServcie;
	  @Value("${zzsbpath}")
	    private String zzsbpath;
	@Autowired
	private ContentService contentService;
	@Autowired
	private ExcelReadService excelReadService;
	@Autowired
	private RemoteBaseService remoteBaseService;
	@Autowired
	private BatchLogService batchLogService;
	  @Autowired
		private DissentAppealSeervice dissentAppealService;

	@Value("${absolutepath}")
	private String absolutepath;

	@Autowired
	private StepLogService stepLogService;
	

	@Autowired
	private TableService tableService;
	
	/**
	 * 查询出所有系统归集的表
	 * 
	 * @param root_id
	 * @param collection_type
	 * @param cube_id_list
	 * @param page
	 * @return
	 */
	@RequestMapping("/selectListForPage.json")
	public RestServiceResult<List<DeclarationManagementForm>> selectListForPage(
			@RequestParam(value = "kId", defaultValue = "", required = false) String root_id,
			@RequestParam(value = "collection_type", defaultValue = "", required = false) String collection_type,
			@RequestParam(value = "cube_id_list", defaultValue = "", required = false) String cube_id_list, Page page) {
		RestServiceResult<List<DeclarationManagementForm>> result = new RestServiceResult<List<DeclarationManagementForm>>();
		List<DeclarationManagementForm> tableList = declarationManagementFormService.selectListForPage(page, root_id,
				collection_type);
		List<String> idList = new ArrayList<String>();
		if (cube_id_list.isEmpty()) {
			result.setData(tableList);
			result.setCount(page.getTotalCount());
			return result;
		} else {
			idList = java.util.Arrays.asList(cube_id_list.split(","));
			for (DeclarationManagementForm a : tableList) {
				for (int i = 0; i < idList.size(); i++) {
					if (a.getCube_id().equals(idList.get(i))) {
						a.setLAY_CHECKED(true);
						;
					}
				}

			}
		}
		result.setData(tableList);
		result.setCount(page.getTotalCount());
		return result;
	}

	/**
	 * 查询出已配置的申报表
	 * 
	 * @param root_id
	 * @param collection_type
	 * @param cube_id_list
	 * @return
	 */
	@RequestMapping("/selectTable.json")
	public RestServiceResult selectTable(
			@RequestParam(value = "kId", defaultValue = "", required = false) String root_id,
			@RequestParam(value = "collection_type", defaultValue = "", required = false) String collection_type,
			@RequestParam(value = "cube_id_list", defaultValue = "", required = false) String cube_id_list) {
		RestServiceResult<Object> result = new RestServiceResult<Object>();
		if (cube_id_list.isEmpty()) {
			return result;
		} else {
			String tableString = (String) cube_id_list.subSequence(0, cube_id_list.length() - 1);
			List<String> idList = new ArrayList<String>();
			idList = java.util.Arrays.asList(cube_id_list.split(","));
			List<DeclarationManagementForm> data = declarationManagementFormService.selectTable(idList, tableString);
			for (DeclarationManagementForm a : data) {
				a.setLAY_CHECKED(true);
				;
			}
			result.setData(data);
		}
		return result;
	}

	@RequestMapping("/selectAllList.json")
	public RestServiceResult<List<DeclarationManagementForm>> selectAllList(
			@RequestParam(value = "kId", defaultValue = "", required = false) String root_id,
			@RequestParam(value = "collection_type", defaultValue = "", required = false) String collection_type,
			@RequestParam(value = "cube_id_list", defaultValue = "", required = false) String cube_id_list) {
		RestServiceResult<List<DeclarationManagementForm>> result = new RestServiceResult<List<DeclarationManagementForm>>();
		List<DeclarationManagementForm> tableList = declarationManagementFormService.selectAllList(root_id,
				collection_type);
		List<String> idList = new ArrayList<String>();
		if (cube_id_list.isEmpty()) {
			result.setData(tableList);
			return result;
		} else {
			idList = java.util.Arrays.asList(cube_id_list.split(","));
			for (DeclarationManagementForm a : tableList) {
				for (int i = 0; i < idList.size(); i++) {
					if (a.getCube_id().equals(idList.get(i))) {
						a.setLAY_CHECKED(true);
						;
					}
				}

			}
		}
		result.setData(tableList);
		return result;
	}
	/**
	 * 门户网站获取自主申报目录
	 * @param condition
	 * @return
	 */
	@IgnoreAuthority
	@RequestMapping("/selectCatalog.json")
	public RestServiceResult selectCatalog(
			@RequestParam(value = "condition", defaultValue = "", required = false) String condition
			) {
		RestServiceResult<Object> result = new RestServiceResult<Object>();
		 Map<String, String>  parseObject = JSONObject.parseObject(condition, Map.class);
		 String type= parseObject.get("type");
		 String root_id= parseObject.get("root_id");
		//获取自主申报目录中系统归集表ID集合
	List<Object> lists =	declarationManagementFormService.getcube_id_list(type,root_id).getData();
	if(lists.size()>0) {
		 Map<String, String>  map = JSONObject.parseObject(lists.get(0).toString(), Map.class);
			String cube_id_list = map.get("cube_id_list");
				String tableString = (String) cube_id_list.subSequence(0, cube_id_list.length() - 1);
				List<String> idList = new ArrayList<String>();
				idList = java.util.Arrays.asList(cube_id_list.split(","));
				List<DeclarationManagementForm> data = declarationManagementFormService.selectTable(idList, tableString);
				for (DeclarationManagementForm a : data) {
					a.setLAY_CHECKED(true);

				}
				//获取目录版本订阅号
				String contentId = declarationManagementFormService.getcontentId();
				result.setData(data);
				result.setMsg(contentId);
	}	
		return result;
	}
	/**
	 * 门户网站添加自主申报
	 *
	 * @param condition
	 * @return
	 */
	@IgnoreAuthority
	@RequestMapping(value = "/addApplication.json")
	public RestServiceResult<Object> addApplication(
			@RequestParam(value = "condition", required = true) String condition, HttpServletRequest request) {
		RestServiceResult<Object> result = new RestServiceResult<>();
		int start = 0;
		int end = 0;
		try {
			Map<String, String> parseObject = JSONObject.parseObject(condition, Map.class);
			String datatype = parseObject.get("datatype");
			String dept = parseObject.get("dept");
			String cube_id = parseObject.get("cube_id");
			String mainType = parseObject.get("mainType");
			String sjly = parseObject.get("sjly");
			// 上传数据base64编码
			String scsj = parseObject.get("scsj");
			// 验证材料base64编码
			String yzcl = parseObject.get("yzcl");
			String scsjfilename = parseObject.get("scsjfilename");
			String yzclfilename = parseObject.get("yzclfilename");
			// 将base64字符解码成字节流
			byte[] decode = Base64.decode(scsj, CharsetUtil.CHARSET_UTF_8);
			byte[] yzcldecode = Base64.decode(yzcl, CharsetUtil.CHARSET_UTF_8);
			 String path = zzsbpath;
			 String time =  DateUtils.getCurrentTimeNumber();
			 //上传数据文件 
			   BufferedOutputStream bos = null;
		        FileOutputStream fos = null;
		        File file = null;
		        try {
		            File dir = new File(path);
		            if (!dir.exists() && dir.isDirectory()) {// 判断文件目录是否存在
		                dir.mkdirs();
		            }
		            file = new File(path + File.separator + time+scsjfilename);
		            fos = new FileOutputStream(file);
		            bos = new BufferedOutputStream(fos);
		            bos.write(decode);
		        } catch (Exception e) {
		            e.printStackTrace();
		        } finally {
		            if (bos != null) {
		                try {
		                    bos.close();
		                } catch (IOException e) {
		                    e.printStackTrace();
		                }
		            }
		            if (fos != null) {
		                try {
		                    fos.close();
		                } catch (IOException e) {
		                    e.printStackTrace();
		                }
		            }
		        }
			 
			 //上传依据文件
			   getFileByBytes(yzcldecode,path, time+yzclfilename);		
			   //将数据放入自主申报历史
			declarationManagementFormService.addApplication(datatype,dept,cube_id,File.separator+time+scsjfilename, File.separator+time+yzclfilename,mainType);
			//将自主申报的数据走数据归集渠道		
			FileItem fileItemzrr = createFileItem(file, "自主申报数据采集");
			Table table = null;
			table = tableService.queryCubeById(Integer.valueOf(cube_id));
			table.setRootId(Integer.valueOf(mainType));
			CommonsMultipartFile applicationfile = new CommonsMultipartFile(fileItemzrr);
			//默认为admin账号采集自主申报数据
			SysUser userInfo = new SysUser();
			userInfo.setUsername("admin");
			userInfo.setOfficeId(51);
			userInfo.setOfficeName("顺义区");
			userInfo.setRealName("超级管理员");
			userInfo.setUserStatus(1);
			userInfo.setUserType(3);
			userInfo.setId(1L);
			String batchId = batchLogService.doUploadFile(table, applicationfile, userInfo, absolutepath);
			// 添加处理流程日志
			stepLogService.addStepLog(batchId, "自主申报上次数据成功,请耐心等待处理结果。");
			result.setMsg("自主申报添加成功！");
			result.setData("添加成功");
			return result;
		} catch (Exception e) {
			ExceptionLogger.error("DeclarationManagementFormController#addApplication", "自主申报添加异常！ERROR:" + e.getMessage(), e);
			result.setCode(RestServiceResult.CODE_UNKNOW);
			result.setMsg("自主申报添加异常！");
			return result;
		}
	}
	@IgnoreAuthority
	@RequestMapping(value = "/getTableList.json")
	public RestServiceResult<List<LinkedHashMap<String, Object>>> getTableList(
			@RequestParam(value = "mainType", defaultValue = "") String mainType,
			@RequestParam(value = "tablename", defaultValue = "") String tablename,
			@RequestParam(value = "mainName", defaultValue = "") String mainName,
			@RequestParam(value = "shzt", defaultValue = "") Integer shzt,
			@RequestParam(value = "condition", defaultValue = "") String condition, Page page,
			HttpServletRequest request) {

		String token = HttpServletHelper.getUserToken(request);
		RestServiceResult<List<LinkedHashMap<String, Object>>> result = new RestServiceResult<List<LinkedHashMap<String, Object>>>();
		// 获取当前用户信息
		RestServiceResult<SysUser> user = remoteBaseService.getCurrentUser(token);
		SysUser userInfo = null;
		if (RestServiceResult.CODE_SUCCESS == user.getCode()) {
			userInfo = user.getData();
			if (null == userInfo || userInfo.getId() <= 0) {
				result.setCode(RestServiceResult.CODE_UNKNOW);
				result.setMsg("系统异常，请稍后再试！");
				ExceptionLogger.error("BatchLogController#getTableList", "未获取到当前用户信息！");
				return result;
			}
		} else {
			result.setCode(user.getCode());
			result.setMsg(user.getMsg());
			return result;
		}

		String[] configColumns = (String[]) MapCache.get(userInfo.getId() + "_" + "process");
		List<String> showColumns = (configColumns == null || configColumns.length == 0)
				? ModifyLogEnum.getDefaultShowColumnEN()
				: Arrays.asList(configColumns);
		// condition="[{columnEN:\"batch_id\",value:\"EX-test-1-20180326-1174\",type:\"varchar\",fuzzy:fasle}]";
		RestServiceResult<List<LinkedHashMap<String, Object>>> r = new RestServiceResult<List<LinkedHashMap<String, Object>>>();
		String[] additionalColumns =  { "id", "tableId", "recordId", "dataId", "bz","yjpath","datapath","sjrdbm","shjg","shdept","shr","shyj"};
		
		
		try {
			List<LinkedHashMap<String, Object>> tableList = declarationManagementFormService.selectByConditionForPage(shzt,mainType,
					tablename, mainName,  showColumns, additionalColumns, condition, page);
			r = new RestServiceResult<List<LinkedHashMap<String, Object>>>(page.getTotalCount(), tableList);
		} catch (Exception e) {
			r.setCode(RestServiceResult.CODE_UNKNOW);
			r.setMsg("系统异常！");
		}
		return r;
	}
	
	@IgnoreAuthority
	@RequestMapping(value = "/getZzsbTableList.json")
	public RestServiceResult<List<LinkedHashMap<String, Object>>> getZzsbTableList(
			@RequestParam(value = "sblb", defaultValue = "") String sblb,
			@RequestParam(value = "ztlx", defaultValue = "") String ztlx,
			 Page page,
			HttpServletRequest request) {

		String token = HttpServletHelper.getUserToken(request);
		RestServiceResult<List<LinkedHashMap<String, Object>>> result = new RestServiceResult<List<LinkedHashMap<String, Object>>>();
		// 获取当前用户信息
		RestServiceResult<SysUser> user = remoteBaseService.getCurrentUser(token);
		SysUser userInfo = null;
		if (RestServiceResult.CODE_SUCCESS == user.getCode()) {
			userInfo = user.getData();
			if (null == userInfo || userInfo.getId() <= 0) {
				result.setCode(RestServiceResult.CODE_UNKNOW);
				result.setMsg("系统异常，请稍后再试！");
				ExceptionLogger.error("BatchLogController#getZzsbTableList", "未获取到当前用户信息！");
				return result;
			}
		} else {
			result.setCode(user.getCode());
			result.setMsg(user.getMsg());
			return result;
		}

		RestServiceResult<List<LinkedHashMap<String, Object>>> r = new RestServiceResult<List<LinkedHashMap<String, Object>>>();
		try {
			
			List<LinkedHashMap<String, Object>> tableList = declarationManagementFormService.selectZzsbTableListForPage(sblb,ztlx, page);
			r = new RestServiceResult<List<LinkedHashMap<String, Object>>>(page.getTotalCount(), tableList);
		} catch (Exception e) {
			r.setCode(RestServiceResult.CODE_UNKNOW);
			r.setMsg("系统异常！");
		}
		return r;
	}
	@IgnoreAuthority
	@RequestMapping(value = "/webSelectHistory.json")
	public RestServiceResult<Object> webSelectHistory(String condition){
		RestServiceResult<Object> r = new RestServiceResult<>();
		Page page  = new Page();
		Map<String,Object> map = JSON.parseObject(condition);
		try {
			page.setLimit(Integer.parseInt(String.valueOf(map.get("limit"))));
			
			page.setPage(Integer.parseInt(String.valueOf(map.get("page"))) /Integer.parseInt(String.valueOf(map.get("limit"))) + 1);
			
			r.setData(declarationManagementFormService.webSelectHistoryForPage(page));
            r.setCount(page.getTotalCount());
		} catch (Exception e) {
			r.setCode(RestServiceResult.CODE_UNKNOW);
			r.setMsg("查询信用承诺失败");
		}
		return r;
	}
	@IgnoreAuthority
	@RequestMapping(value = "/getDetail.json")
	public RestServiceResult<Map<String,Object>> updateCheckById(@RequestParam(value = "id", defaultValue = "") String id,		
			@RequestParam(value = "tableId", defaultValue = "") String tableId,
			@RequestParam(value = "dept", defaultValue = "") String dept,
			@RequestParam(value = "path", defaultValue = "") String path
) {
		RestServiceResult<Map<String,Object>>  r = new RestServiceResult<Map<String,Object>> ();
		//获取该记录对应上报的信息
		 String fileType = path.substring(path.lastIndexOf(".") + 1);
		 path = zzsbpath+path;
	        // return a list contains many list
	        List<List<String>> lists = new ArrayList<List<String>>();
	        //读取excel文件
	        InputStream is = null;
	        try {
	            is = new FileInputStream(path);
	            //获取工作薄
	            Workbook wb = null;
	            if (fileType.equals("xls")) {
	                wb = new HSSFWorkbook(is);
	            } else if (fileType.equals("xlsx")) {
	                wb = new XSSFWorkbook(is);
	            } else {
	                return null;
	            }
	            //读取第一个工作页sheet
	            Sheet sheet = wb.getSheetAt(0);
		Table table = tableServcie.queryCubeById(Integer.valueOf(tableId));
		 String tipId = tableId + "_" + dept;
		TableResult tableResult = contentService.getTableColumns(Integer.valueOf(tableId), 3, tipId);
		List<Column> columns = tableResult.getColumns();
		String tablename = 	"t_"+table.getResourceId();
		int allRowNum = sheet.getLastRowNum();
		List<Object> list = new ArrayList<Object>();
		// 获取数据
		List<Map<String, Object>>	listDataMap = excelReadService.readExcelData(table,0, allRowNum, sheet, dept, columns);
		listDataMap.remove(0);
		//获取字段信息
		//获取该表所有字段
   		List<Map<String,String>> basedata =	dissentAppealService.selectBaseData(null,tablename);
   		Map<String, Object> map = new HashMap<String, Object>();
   	
   		map.put("checkdata", listDataMap);
   		map.put("Columns", basedata);
   		r.setData(map);
		} catch (Exception e) {
			r.setCode(RestServiceResult.CODE_UNKNOW);
			r.setMsg("获取详情失败！");
		}
			return r;

	}
	/**
	 * 
	 * @param id
	 * @param shjg	审核结果	
	 * @param shyj	审核意见
	 * @param sjurl	数据文件地址
	 * @param request
	 * @return
	 */
	@IgnoreAuthority
	@RequestMapping(value = "/updateApplication.json")
	public RestServiceResult<Map<String,Object>> updateApplication(@RequestParam(value = "id", defaultValue = "") String id,		
			@RequestParam(value = "shjg", defaultValue = "") String shjg,
			@RequestParam(value = "shyj", defaultValue = "") String shyj,
			@RequestParam(value = "sjurl", defaultValue = "") String sjurl,
			@RequestParam(value = "tableId", defaultValue = "") Integer tableId,
			HttpServletRequest request) {
		RestServiceResult<Map<String,Object>>  result = new RestServiceResult<Map<String,Object>> ();

		String token = HttpServletHelper.getUserToken(request);
		// 获取当前用户信息
		RestServiceResult<SysUser> user = remoteBaseService.getCurrentUser(token);
		SysUser userInfo = null;
		if (RestServiceResult.CODE_SUCCESS == user.getCode()) {
			userInfo = user.getData();
			if (null == userInfo || userInfo.getId() <= 0) {
				result.setCode(RestServiceResult.CODE_UNKNOW);
				result.setMsg("系统异常，请稍后再试！");
				ExceptionLogger.error("BatchLogController#getTableList", "未获取到当前用户信息！");
				return result;
			}
		} else {
			result.setCode(user.getCode());
			result.setMsg(user.getMsg());
			return result;
		}
		try {
			if(shjg.equals("数据真实，审核通过")) {
				//审核通过将该自主申报数据上传
			FileOutputStream file2 = new FileOutputStream( new File(sjurl));		
			FileItem fileItemzrr = createFileItem(new File(sjurl), "自主申报数据采集");
			Table table = null;
			table.setRootId(tableId);
			CommonsMultipartFile applicationfile = new CommonsMultipartFile(fileItemzrr);
			String batchId = batchLogService.doUploadFile(table, applicationfile, userInfo, absolutepath);
			// 添加处理流程日志
			stepLogService.addStepLog(batchId, "文件上传完成,请耐心等待处理结果。");
				
			}
			declarationManagementFormService.updateApplication(id,shjg,shyj,userInfo.getOfficeName(),userInfo.getRealName());
			
		} catch (Exception e) {
			result.setCode(RestServiceResult.CODE_UNKNOW);
			result.setMsg("审核失败！");
		}
			return result;

	}
	
	
	
	 /**
     * 下载文件
     * 
     * @param response
     * @throws IOException
     */
    @IgnoreAuthority
    @RequestMapping("/export.json")
    public void exportxzxkTemplate(String url,HttpServletResponse response) throws IOException {
    	 
    	 String path = zzsbpath + url;
      FileUtil.downloadFile(path, response);

    }
	public static boolean isRowEmpty(Row row) {

		for (int c = row.getFirstCellNum(); c < row.getLastCellNum(); c++) {

			Cell cell = row.getCell(c);

			if (cell != null && cell.getCellType() != Cell.CELL_TYPE_BLANK)

				return false;

		}
		return true;

	}
	//将Byte数组转换成文件
    public static void getFileByBytes(byte[] bytes, String filePath, String fileName) {
        BufferedOutputStream bos = null;
        FileOutputStream fos = null;
        File file = null;
        try {
            File dir = new File(filePath);
            if (!dir.exists() && dir.isDirectory()) {// 判断文件目录是否存在
                dir.mkdirs();
            }
            file = new File(filePath + File.separator + fileName);
            fos = new FileOutputStream(file);
            bos = new BufferedOutputStream(fos);
            bos.write(bytes);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (bos != null) {
                try {
                    bos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (fos != null) {
                try {
                    fos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
    public static List<List<String>> readExcel(String path) {
        String fileType = path.substring(path.lastIndexOf(".") + 1);
        // return a list contains many list
        List<List<String>> lists = new ArrayList<List<String>>();
        //读取excel文件
        InputStream is = null;
        try {
            is = new FileInputStream(path);
            //获取工作薄
            Workbook wb = null;
            if (fileType.equals("xls")) {
                wb = new HSSFWorkbook(is);
            } else if (fileType.equals("xlsx")) {
                wb = new XSSFWorkbook(is);
            } else {
                return null;
            }

            //读取第一个工作页sheet
            Sheet sheet = wb.getSheetAt(0);
            //第一行为标题
            for (Row row : sheet) {
                ArrayList<String> list = new ArrayList<String>();
                for (Cell cell : row) {
                    //根据不同类型转化成字符串
                    cell.setCellType(Cell.CELL_TYPE_STRING);
                    list.add(cell.getStringCellValue());
                }
                lists.add(list);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (is != null) is.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return lists;
    }
 // 把File转化为CommonsMultipartFile
 	public FileItem createFileItem(File file, String fieldName) {
 		// DiskFileItemFactory()：构造一个配置好的该类的实例
 		// 第一个参数threshold(阈值)：以字节为单位.在该阈值之下的item会被存储在内存中，在该阈值之上的item会被当做文件存储
 		// 第二个参数data
 		// repository：将在其中创建文件的目录.用于配置在创建文件项目时，当文件项目大于临界值时使用的临时文件夹，默认采用系统默认的临时文件路径
 		FileItemFactory factory = new DiskFileItemFactory(16, null);
 		// fieldName：表单字段的名称；第二个参数 ContentType；第三个参数isFormField；第四个：文件名
 		FileItem item = factory.createItem(fieldName, "text/plain", true, file.getName());
 		int bytesRead = 0;
 		byte[] buffer = new byte[8192];
 		FileInputStream fis = null;
 		OutputStream os = null;
 		try {
 			fis = new FileInputStream(file);
 			os = item.getOutputStream();
 			while ((bytesRead = fis.read(buffer, 0, 8192)) != -1) {
 				os.write(buffer, 0, bytesRead);// 从buffer中得到数据进行写操作
 			}
 		} catch (IOException e) {
 			e.printStackTrace();
 		} finally {
 			try {
 				if (os != null) {
 					os.close();
 				}
 				if (fis != null) {
 					fis.close();
 				}
 			} catch (IOException e) {
 				e.printStackTrace();
 			}
 		}
 		return item;
 	}

}
